import React, { useState, useEffect } from 'react';
import { Card, Typography, Row, Col, Table, Button, Modal, Form, Input, message, Space } from 'antd';
import type { TableProps } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons';
import { fetchEssays, createEssay, updateEssay, deleteEssay } from '../../services/manipulate.ts';
import './darkTheme.css';
import './quillCustom.css';
import parse from 'html-react-parser';
import ReactQuill from 'react-quill';
import 'react-quill/dist/quill.snow.css';

const { Title, Paragraph, Text } = Typography;
const { TextArea } = Input;

interface Essay {
  id?: number;
  title: string;
  source: string;
  full_text: string;
  created_at?: string;
}

interface DataItem {
  key: string;
  index: number;
  id?: number;
  title: string;
  source: string;
  date: string;
  full_text: string;
}

const EssaySet = () => {
  const [selectedContent, setSelectedContent] = useState<string>('请点击左侧表格中的条目查看详细内容');
  const [data, setData] = useState<DataItem[]>([]);
  const [loading, setLoading] = useState<boolean>(false);
  const [isModalVisible, setIsModalVisible] = useState<boolean>(false);
  const [isEditing, setIsEditing] = useState<boolean>(false);
  const [currentRecord, setCurrentRecord] = useState<DataItem | null>(null);
  const [form] = Form.useForm();
  const [searchKeyword, setSearchKeyword] = useState<string>('');
  const [highlightedData, setHighlightedData] = useState<DataItem[]>([]);
  const [pageSize, setPageSize] = useState<number>(10);
  const [editorContent, setEditorContent] = useState<string>('');
  
  // 拖拽相关状态
  const [isDragging, setIsDragging] = useState<boolean>(false);
  const [dragOffset, setDragOffset] = useState<{ x: number; y: number }>({ x: 0, y: 0 });
  const [modalPosition, setModalPosition] = useState<{ x: number; y: number }>({ x: 0, y: 0 });

  // 获取文章数据
  useEffect(() => {
    fetchData();
  }, []);

  // 拖拽功能实现
  const handleMouseDown = (e: React.MouseEvent) => {
    e.preventDefault();
    const modal = document.querySelector('.ant-modal') as HTMLElement;
    if (modal) {
      const rect = modal.getBoundingClientRect();
      // 如果Modal还没有被拖拽过，使用当前位置作为起始位置
      const currentX = modalPosition.x || rect.left;
      const currentY = modalPosition.y || rect.top;
      
      setDragOffset({
        x: e.clientX - currentX,
        y: e.clientY - currentY
      });
      setIsDragging(true);
    }
  };

  const handleMouseMove = (e: MouseEvent) => {
    if (isDragging) {
      e.preventDefault();
      const newX = e.clientX - dragOffset.x;
      const newY = e.clientY - dragOffset.y;
      
      // 限制拖拽范围，防止拖出屏幕
      const maxX = window.innerWidth - 600; // Modal宽度的一半
      const maxY = window.innerHeight - 100;
      
      setModalPosition({ 
        x: Math.max(0, Math.min(newX, maxX)), 
        y: Math.max(0, Math.min(newY, maxY)) 
      });
    }
  };

  const handleMouseUp = () => {
    setIsDragging(false);
  };

  useEffect(() => {
    if (isDragging) {
      document.addEventListener('mousemove', handleMouseMove);
      document.addEventListener('mouseup', handleMouseUp);
      return () => {
        document.removeEventListener('mousemove', handleMouseMove);
        document.removeEventListener('mouseup', handleMouseUp);
      };
    }
  }, [isDragging, dragOffset]);

  const fetchData = async () => {
    try {
      setLoading(true);
      const essays = await fetchEssays();
      console.log('essays  2222:', essays)
      const formattedData = essays.map((essay, index) => ({
        key: essay.id?.toString() || index.toString(),
        index: index + 1,
        id: essay.id,
        title: essay.title,
        source: essay.source,
        date: essay.created_at ? new Date(essay.created_at).toLocaleDateString() : '',
        full_text: essay.full_text,

      }));
      setData(formattedData);
    } catch (error) {
      console.error('获取文章数据失败:', error);
      message.error('获取文章数据失败');
    } finally {
      setLoading(false);
    }
  };

  const columns: TableProps<DataItem>['columns'] = [
    {
      title: '序号',
      dataIndex: 'index',
      key: 'index',
      width: 50,
      align: 'center',
    },
    {
      title: '标题',
      dataIndex: 'title',
      key: 'title',
      width: 200,
      align: 'center',
      render: (text) => parse(text),
    },
    {
      title: '来源',
      dataIndex: 'source',
      key: 'source',
      align: 'center',
      width: 120,
    },
    {
      title: '日期',
      dataIndex: 'date',
      key: 'date',
      align: 'center',
      width: 80,
    },
    {
      title: '操作',
      key: 'action',
      align: 'center',
      width: 80,
      render: (_, record) => (
        <Space size="middle">
          <Button 
            type="text" 
            icon={<EditOutlined />} 
            onClick={() => showModal(record)}
            style={{ color: '#ccd6f6' }}
          />
          <Button 
            type="text" 
            icon={<DeleteOutlined />} 
            onClick={() => handleDelete(record)}
            style={{ color: '#ff4d4f' }}
          />
        </Space>
      ),
    },
  ];

  // 处理新增文章
  const showModal = (record?: DataItem) => {
    form.resetFields();
    if (record) {
      setIsEditing(true);
      setCurrentRecord(record);
      setEditorContent(record.full_text);
      form.setFieldsValue({
        title: record.title,
        source: record.source
      });

    } else {
      setIsEditing(false);
      setCurrentRecord(null);
      setEditorContent('');
    }
    setIsModalVisible(true);
  };

  const handleOk = async () => {
    try {
      const values = await form.validateFields();
      
      if (isEditing && currentRecord) {
        const updatedEssay: Essay = {
          id: currentRecord.id,
          title: values.title,
          source: values.source,
          full_text: editorContent
        };
        console.log('updatedEssay:', updatedEssay);
        await updateEssay(updatedEssay.id!, updatedEssay);
        message.success('文章更新成功');
      } else {
        const newEssay: Essay = {
          title: values.title,
          source: values.source,
          full_text: editorContent
        };
        console.log('newEssay:', newEssay);

        await createEssay(newEssay);
        message.success('文章创建成功');
      }
      
      setIsModalVisible(false);
      setEditorContent('');
      fetchData(); // 重新获取数据
    } catch (error) {
      console.error('提交表单失败:', error);
      message.error(isEditing ? '更新文章失败' : '创建文章失败');
    }
  };

  const handleCancel = () => {
    setIsModalVisible(false);
    setEditorContent('');
    // 重置拖拽位置
    setModalPosition({ x: 0, y: 0 });
    setIsDragging(false);
  };

  const handleDelete = (record: DataItem) => {
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除文章"${record.title}"吗？此操作不可撤销。`,
      okText: '确认删除',
      cancelText: '取消',
      okType: 'danger',
      onOk: async () => {
        try {
          if (record.id) {
            await deleteEssay(record.id);
            message.success('文章删除成功');
            fetchData(); // 重新获取数据
          }
        } catch (error) {
          console.error('删除文章失败:', error);
          message.error('删除文章失败');
        }
      }
    });
  };

  const handleRowClick = (record: DataItem) => {
    setSelectedContent(record.full_text);
  };

  const handleSearch = () => {
    if (!searchKeyword.trim()) {
      setHighlightedData([]);
      return;
    }

    const keyword = searchKeyword.toLowerCase();
    const highlighted = data.map(item => ({
      ...item,
      title: item.full_text.toLowerCase().includes(keyword) 
        ? `<span style="background-color: yellow">${item.title}</span>` 
        : item.title,
      full_text: item.full_text.toLowerCase().includes(keyword)
        ? item.full_text.replace(new RegExp(keyword, 'gi'), match => `<span style="background-color: yellow">${match}</span>`)
        : item.full_text
    }));

    setHighlightedData(highlighted);
  };

  // 图片上传处理
  const handleUploadChange = ({ fileList: newFileList }: { fileList: UploadFile[] }) => {
    setFileList(newFileList);
  };

  // 自定义上传函数
  const customUpload = ({ file, onSuccess, onError }: any) => {
    // 模拟上传过程
    setTimeout(() => {
      const reader = new FileReader();
      reader.onload = (e) => {
        const imageUrl = e.target?.result as string;
        onSuccess({ url: imageUrl });
      };
      reader.readAsDataURL(file);
    }, 1000);
  };

  // 插入图片到编辑器
  const insertImageToEditor = (imageUrl: string) => {
    const quill = (document.querySelector('.ql-editor') as any)?.__quill;
    if (quill) {
      const range = quill.getSelection();
      const index = range ? range.index : quill.getLength();
      quill.insertEmbed(index, 'image', imageUrl);
      quill.setSelection(index + 1);
    }
  };

  // ReactQuill 配置
  const quillModules = {
    toolbar: [
      [{ 'header': [1, 2, false] }],
      ['bold', 'italic', 'underline', 'strike'],
      [{ 'list': 'ordered'}, { 'list': 'bullet' }],
      ['blockquote', 'code-block'],
      ['link', 'image'],
      ['clean']
    ],
  };

  const quillFormats = [
    'header', 'bold', 'italic', 'underline', 'strike',
    'list', 'bullet', 'blockquote', 'code-block',
    'link', 'image'
  ];

  return (
    <div style={{ padding: '20px', backgroundColor: '#0a192f', minHeight: '100vh' }}>
      <Row gutter={16}>
        <Col span={12}>
          <Card 
            title={
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <span>策略列表</span>
                <Space>
                  <Input.Search
                    placeholder="输入关键字搜索"
                    value={searchKeyword}
                    onChange={(e) => setSearchKeyword(e.target.value)}
                    onSearch={handleSearch}
                    style={{ width: 200 }}
                  />
                  <Button 
                    type="primary" 
                    icon={<PlusOutlined />} 
                    onClick={() => showModal()}
                    style={{ backgroundColor: '#64ffda', borderColor: '#64ffda', color: '#0a192f' }}
                  >
                  新增文章
                </Button>
                </Space>
              </div>
            }
            bordered={false} 
            style={{ 
              height: 'calc(100vh - 180px)', 
              overflow: 'auto',
              backgroundColor: '#112240',
              color: '#ccd6f6',
              borderColor: '#233554'
            }}
            headStyle={{ color: '#ccd6f6', backgroundColor: '#112240', borderColor: '#233554' }}
          >
            <Table 
              columns={columns} 
              dataSource={highlightedData.length > 0 ? highlightedData : data} 
              loading={loading}
              scroll={{ y: 1000 }}
              pagination={false}
              size="middle"
              onRow={(record) => ({
                onClick: () => handleRowClick(record),
                style: { cursor: 'pointer' }
              })}
              style={{ 
                backgroundColor: '#112240',
                color: '#8892b0'
              }}
              className="dark-theme-table"
            />
          </Card>
        </Col>
        <Col span={12}>
          <Card 
            title="策略详情" 
            bordered={false} 
            style={{ 
              height: 'calc(100vh - 180px)', 
              overflow: 'auto',
              backgroundColor: '#112240',
              color: '#ccd6f6',
              borderColor: '#233554',
              boxShadow: '0 1px 2px rgba(0, 0, 0, 0.2)'
            }}
            headStyle={{ color: '#ccd6f6', backgroundColor: '#112240', borderColor: '#233554' }}
          >
            <div style={{ padding: '16px' }}>
              <div 
                style={{ 
                  fontSize: '16px', 
                  lineHeight: '1.8', 
                  color: '#8892b0',
                  minHeight: '200px'
                }}
                dangerouslySetInnerHTML={{ __html: selectedContent }}
              />
            </div>
          </Card>
        </Col>
      </Row>

      {/* 新增文章对话框 */}
      <Modal
        title={
          <div 
            onMouseDown={handleMouseDown}
            style={{ 
              cursor: isDragging ? 'grabbing' : 'grab',
              userSelect: 'none',
              padding: '8px 0',
              WebkitUserSelect: 'none',
              MozUserSelect: 'none',
              msUserSelect: 'none'
            }}
          >
            {isEditing ? "编辑文章" : "新增文章"}
          </div>
        }
        visible={isModalVisible}
        onOk={handleOk}
        onCancel={handleCancel}
        okText="确定"
        cancelText="取消"
        width={1200}
        maskClosable={false}
        style={{ 
          top: modalPosition.y || 20,
          left: modalPosition.x || undefined,
          transform: modalPosition.x ? 'none' : undefined,
          position: modalPosition.x ? 'fixed' : 'relative'
        }}
      >
        <Form
          form={form}
          layout="vertical"
          name="createEssayForm"
        >
          <Form.Item
            name="title"
            label="标题标签"
            rules={[{ required: true, message: '请输入标题标签' }]}
          >
            <Input placeholder="请输入标题标签" />
          </Form.Item>
          <Form.Item
            name="source"
            label="来源"
            rules={[{ required: true, message: '请输入来源' }]}
          >
            <Input placeholder="请输入来源" />
          </Form.Item>

          <Form.Item
            label="全文内容"
            required
          >
            <ReactQuill
              theme="snow"
              value={editorContent}
              onChange={setEditorContent}
              modules={quillModules}
              formats={quillFormats}
              style={{ 
                height: '300px', 
                marginBottom: '50px',
                backgroundColor: 'white'
              }}
              placeholder="请输入全文内容..."
            />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default EssaySet;